package com.ghck.server.service.aggregation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ghck.server.dao.AjkAccountMapper;
import com.ghck.server.dao.UsersMapper;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.exception.GhckException;
import com.ghck.server.model.AjkAccount;
import com.ghck.server.model.UserRole;
import com.ghck.server.model.Users;
import com.ghck.shop.model.Seller;
import com.ghck.shop.service.SellerService;

@Service
@Transactional
public class SellerAggregationService {
	
	@Autowired
	private SellerService sellerService;
	@Autowired
	private AjkAccountMapper ajkAccountMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private UserCache userCache;
	
	@Transactional
	public void sellerPass(Seller seller) {
		Seller dbSeller = sellerService.findSellerById(seller.getId());
		if(dbSeller == null){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"该商家申请不存在");
			throw exception;
		}else {
			if(1 == dbSeller.getStatus()){
				GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"该商家已经审核过了");
				throw exception;
			}
		}
		AjkAccount aa = ajkAccountMapper.findByUserId(dbSeller.getUserId());
		if(aa != null){
			userCache.removeUserFromCache(aa.getAccessId());
			sellerService.updateSellerStatus(seller.getId(), 1);
			aa.setRole(UserRole.SHOP.ordinal());
			ajkAccountMapper.update(aa);
			Users user = new Users();
			user.setId(dbSeller.getUserId());
			user.setRole(UserRole.SHOP.ordinal());
			usersMapper.update(user);
		}
		
	}
}
